package com.hjf.booking.security.config;

import com.hjf.booking.security.filter.JwtAuthenticationFilter;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.stereotype.Component;

/**
 * @author hjf
 * @date 2021-03-25 16:15
 */
@Component
public class JwtAuthenticationConfigure<T extends JwtAuthenticationConfigure<T,B>,B extends HttpSecurityBuilder<B>> extends AbstractHttpConfigurer<T,B> {

    private JwtAuthenticationFilter authFilter;

    public JwtAuthenticationConfigure() {
        this.authFilter = new JwtAuthenticationFilter();
    }

    @Override
    public void configure(B http) throws Exception {
        authFilter.setAuthenticationManager(http.getSharedObject(AuthenticationManager.class));
        authFilter.setFailureHandler(new LoginFailureHandler());

        JwtAuthenticationFilter filter =postProcess(authFilter);
        http.addFilterBefore(filter, LogoutFilter.class);
    }


    public JwtAuthenticationConfigure<T, B> permissiveRequestUrls(String ... urls){
        authFilter.setPermissiveRequestMatchers(urls);
        return this;
    }

    public JwtAuthenticationConfigure<T, B> tokenValidSuccessHandler(AuthenticationSuccessHandler successHandler){
        authFilter.setSuccessHandler(successHandler);
        return this;
    }

}
